#include <interfacelib/directx/vertexbuffermanager.h>
#include <dxerr9.h>
#include <utillib/memory/memory.h>

using namespace interfacelib::DirectX;

VertexBufferManager::VertexBufferManager() : m_recreateVertexBuffer( false )
{
}

VertexBufferManager::~VertexBufferManager()
{
	release();
}

void VertexBufferManager::release()
{
	{
		vertexBufferList::const_iterator iter_end( m_vertexList.end() );
		for ( vertexBufferList::const_iterator iter = m_vertexList.begin() ; iter != iter_end; ++iter )
		{
			VertexBuffer *vertexBuffer = ( *iter );
			
			SAFE_RELEASE( vertexBuffer->vertexBuffer );
			SAFE_DELETE( vertexBuffer );
		}
		m_vertexList.clear();
	}	
}

void VertexBufferManager::releaseVertexBuffer()
{
	if ( m_recreateVertexBuffer )
	{
		vertexBufferList::const_iterator iter_end( m_vertexList.end() );
		for ( vertexBufferList::const_iterator iter = m_vertexList.begin() ; iter != iter_end; ++iter )
		{
			VertexBuffer *vertexBuffer = ( *iter );
			
			SAFE_RELEASE( vertexBuffer->vertexBuffer );
		}
	}
}

interfacelib::DirectX::VertexBufferManager::VertexBuffer *VertexBufferManager::createVertexBuffer( UINT length, DWORD usage, DWORD fvf, D3DPOOL pool , HANDLE *handle )
{
	VertexBuffer *vertexBuffer = new VertexBuffer;
	vertexBuffer->length = length;
	vertexBuffer->usage = usage;
	vertexBuffer->fvf = fvf;
	vertexBuffer->pool = pool;
	vertexBuffer->handle = handle;
	vertexBuffer->vertexBuffer = NULL;

	insertVertexBuffer( vertexBuffer );

	createVertexBuffer( vertexBuffer );
	
	return ( vertexBuffer );
}


void VertexBufferManager::createVertexBuffer( interfacelib::DirectX::VertexBufferManager::VertexBuffer *vertexBuffer )
{
	if ( vertexBuffer->vertexBuffer ) return;

	HRESULT hr = m_D3DDevice->CreateVertexBuffer( vertexBuffer->length, vertexBuffer->usage, vertexBuffer->fvf, vertexBuffer->pool, &vertexBuffer->vertexBuffer, vertexBuffer->handle );

	if ( FAILED ( hr ) )
	{
		const char *buffer = DXGetErrorString9A( hr );
	}
}

void VertexBufferManager::insertVertexBuffer( interfacelib::DirectX::VertexBufferManager::VertexBuffer *vertexBuffer )
{
	{
		vertexBufferList::iterator iter = m_vertexList.find( vertexBuffer );
		if ( iter == m_vertexList.end() )
		{
			m_vertexList.insert( vertexBuffer );
		}
	}
}

void VertexBufferManager::releaseVertexBuffer( interfacelib::DirectX::VertexBufferManager::VertexBuffer *vertexBuffer )
{
	if ( m_recreateVertexBuffer )
	{
		SAFE_RELEASE( vertexBuffer->vertexBuffer );
	}
}